<template>
  <div class="shop">
    <h1>商品列表</h1>
    <div class="product-list">
      <div v-for="product in products" :key="product.id" class="product-item">
        <img :src="product.image" :alt="product.name" />
        <div class="product-info">
          <h3>{{ product.name }}</h3>
          <p class="price">¥{{ product.price.toFixed(2) }}</p>
          <div class="button-group">
            <button @click="addToCart(product)" class="add-to-cart">加入购物车</button>
            <button @click="buyNow(product)" class="buy-now">立即购买</button>
          </div>
        </div>
      </div>
    </div>
    <div v-if="showNotification" class="notification">
      {{ notificationMessage }}
    </div>
  </div>
</template>
<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useProductStore } from '../stores/productStore';
import { useCartStore } from '../stores/cartStore';
const router = useRouter();
const productStore = useProductStore();
const cartStore = useCartStore();
const products = productStore.products;
const showNotification = ref(false);
const notificationMessage = ref('');
const addToCart = (product) => {
  cartStore.addItem(product);
  notificationMessage.value = `${product.name} 已添加到购物车`;
  showNotification.value = true;
  setTimeout(() => {
    showNotification.value = false;
  }, 3000); // 3秒后隐藏提示
};
const buyNow = (product) => {
  cartStore.clearCart(); // 清空购物车
  cartStore.addItem(product); // 添加当前商品
  router.push('/Order/payment'); // 跳转到支付页面
};
</script>
<style scoped>
.shop {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}
h1 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}
.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}
.product-item {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  transition: box-shadow 0.3s ease;
}
.product-item:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.product-item img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}
.product-info {
  padding: 15px;
}
.product-info h3 {
  margin: 0 0 10px;
  font-size: 1.2em;
  color: #333;
}
.price {
  font-weight: bold;
  color: #e53935;
  margin-bottom: 10px;
}
.add-to-cart,
.buy-now {
  width: 48%;
  padding: 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}
.add-to-cart {
  background-color: #4caf50;
  color: white;
}
.buy-now {
  background-color: #f44336;
  color: white;
}
.add-to-cart:hover {
  background-color: #45a049;
}
.buy-now:hover {
  background-color: #d32f2f;
}
@media (max-width: 768px) {
  .product-list {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  }
}
.notification {
  position: fixed;
  bottom: 20px;
  right: 20px;
  background-color: #4caf50;
  color: white;
  padding: 15px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  transition: opacity 0.3s ease;
}
</style>
